package com.android.demos.module.wificonnect;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioGroup;

import com.aaron.android.framework.base.mvp.presenter.BasePresenter;
import com.aaron.android.framework.base.widget.recycleview.OnRecycleViewItemClickListener;
import com.aaron.android.framework.base.widget.refresh.NetworkPagerLoaderViewActivity;
import com.aaron.android.framework.base.widget.refresh.NetworkSwipeRecyclerRefreshPagerLoaderFragment;
import com.aaron.android.framework.base.widget.refresh.PullMode;
import com.aaron.android.framework.utils.DisplayUtils;
import com.android.demos.R;
import com.android.demos.module.wificonnect.adapter.WifiListAdapter;

import java.util.List;

/**
 * Created on 16/11/1.
 *
 * @author aaron.huang
 * @version 1.0.0
 */

public class WifiAutoConnectActivity extends NetworkPagerLoaderViewActivity<WifiAutoConnectActivity.WifiAutoConnectFragment> {

    @Override
    public WifiAutoConnectFragment createNetworkPagerLoaderFragment(Context context) {
        return new WifiAutoConnectFragment();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("Wifi选择连接");

    }

    public static class WifiAutoConnectFragment extends NetworkSwipeRecyclerRefreshPagerLoaderFragment<BasePresenter> {

        private WifiAdmin mWifiAdmin;
        private WifiListAdapter mWifiListAdapter;

        @Override
        protected void requestData(int page) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mWifiListAdapter.setData(getWifiList());
                    mWifiListAdapter.notifyDataSetChanged();
                    requestSuccess();
                }
            }, 2000);
        }

        @Override
        protected void initViews() {
            setPullMode(PullMode.PULL_DOWN);
            mWifiListAdapter = new WifiListAdapter(getActivity());
            mWifiAdmin = new WifiAdmin(getActivity());
            mWifiAdmin.openWifi();
            setRecyclerAdapter(mWifiListAdapter);
//            setDivider(R.drawable.main_recycler_divider);
            int padding = DisplayUtils.dp2px(8);
            setRecyclerViewPadding(padding, padding, padding, padding);
            mWifiListAdapter.setOnRecycleViewItemClickListener(new OnRecycleViewItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
//                    PopupUtils.showToast(mWifiListAdapter.getDataList().get(position).SSID);
                    View dialogCustomView = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_wifi_connect, null);
                    RadioGroup radioGroup = (RadioGroup) dialogCustomView.findViewById(R.id.wifi_type_radioGroup);
//                    int type = radioGroup.g
                    radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(RadioGroup group, int checkedId) {

                        }
                    });
                }

                @Override
                public boolean onItemLongClick(View view, int position) {
                    return false;
                }
            });
        }

        private List<ScanResult> getWifiList() {
            mWifiAdmin.openWifi();
            mWifiAdmin.startScan();
            return mWifiAdmin.mWifiAdapterList;
        }

        @Override
        public void setPresenter() {

        }
    }

    public static class WifiAdmin {
        private WifiManager mWifiManager;
        private WifiInfo mWifiInfo;
        private List<ScanResult> mWifiAdapterList;
        private List<WifiConfiguration> mWifiConfigurationList;
        private WifiManager.WifiLock mWifiLock;

        public WifiAdmin(Context context) {
            // 取得WifiManager对象
            mWifiManager = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            // 取得WifiInfo对象
            mWifiInfo = mWifiManager.getConnectionInfo();
        }

        /**
         * 打开wifi
         */
        public void openWifi() {
            if (!mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(true);
            }
        }

        /**
         * 关闭wifi
         */
        public void closeWifi() {
            if (mWifiManager.isWifiEnabled()) {
                mWifiManager.setWifiEnabled(false);
            }
        }

        /**
         * 检查当前wifi状态
         *
         * @return state
         */
        public int checkState() {
            return mWifiManager.getWifiState();
        }

        /**
         * 锁定WifiLock
         */
        public void acquireWifiLock() {
            mWifiLock.acquire();
        }

        /**
         * 解锁WifiLock
         */
        public void releaseWifiLock() {
            // 判断时候锁定
            if (mWifiLock.isHeld()) {
                mWifiLock.acquire();
            }
        }

        /**
         * 创建一个WifiLock
         */
        public void creatWifiLock() {
            mWifiLock = mWifiManager.createWifiLock("Test");
        }

        // 得到配置好的网络
        public List<WifiConfiguration> getConfiguration() {
            return mWifiConfigurationList;
        }

        // 指定配置好的网络进行连接
        public void connectConfiguration(int index) {
            // 索引大于配置好的网络索引返回
            if (index > mWifiConfigurationList.size()) {
                return;
            }
            // 连接配置好的指定ID的网络
            mWifiManager.enableNetwork(mWifiConfigurationList.get(index).networkId,
                    true);
        }

        public void startScan() {
            mWifiManager.startScan();
            // 得到扫描结果
            mWifiAdapterList = mWifiManager.getScanResults();
            // 得到配置好的网络连接
            mWifiConfigurationList = mWifiManager.getConfiguredNetworks();
        }

        // 得到网络列表
        public List<ScanResult> getWifiList() {
            return mWifiAdapterList;
        }

        // 查看扫描结果
        public StringBuilder lookUpScan() {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < mWifiAdapterList.size(); i++) {
                stringBuilder
                        .append("Index_" + new Integer(i + 1).toString() + ":");
                // 将ScanResult信息转换成一个字符串包
                // 其中把包括：BSSID、SSID、capabilities、frequency、level
                stringBuilder.append((mWifiAdapterList.get(i)).toString());
                stringBuilder.append("/n");
            }
            return stringBuilder;
        }

        // 得到MAC地址
        public String getMacAddress() {
            return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
        }

        // 得到接入点的BSSID
        public String getBSSID() {
            return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
        }

        // 得到IP地址
        public int getIPAddress() {
            return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
        }

        // 得到连接的ID
        public int getNetworkId() {
            return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
        }

        // 得到WifiInfo的所有信息包
        public String getWifiInfo() {
            return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
        }

        // 添加一个网络并连接
        public void addNetwork(WifiConfiguration wcg) {
            int wcgID = mWifiManager.addNetwork(wcg);
            boolean b = mWifiManager.enableNetwork(wcgID, true);
            System.out.println("a--" + wcgID);
            System.out.println("b--" + b);
        }

        // 断开指定ID的网络
        public void disconnectWifi(int netId) {
            mWifiManager.disableNetwork(netId);
            mWifiManager.disconnect();
        }

        //然后是一个实际应用方法，只验证过没有密码的情况：

        public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
            WifiConfiguration config = new WifiConfiguration();
            config.allowedAuthAlgorithms.clear();
            config.allowedGroupCiphers.clear();
            config.allowedKeyManagement.clear();
            config.allowedPairwiseCiphers.clear();
            config.allowedProtocols.clear();
            config.SSID = "\"" + SSID + "\"";

            WifiConfiguration tempConfig = this.IsExsits(SSID);
            if (tempConfig != null) {
                mWifiManager.removeNetwork(tempConfig.networkId);
            }

            if (Type == 1) //WIFICIPHER_NOPASS
            {
                config.wepKeys[0] = "";
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                config.wepTxKeyIndex = 0;
            }
            if (Type == 2) //WIFICIPHER_WEP
            {
                config.hiddenSSID = true;
                config.wepKeys[0] = "\"" + Password + "\"";
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
                config.wepTxKeyIndex = 0;
            }
            if (Type == 3) //WIFICIPHER_WPA
            {
                config.preSharedKey = "\"" + Password + "\"";
                config.hiddenSSID = true;
                config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
                config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                config.status = WifiConfiguration.Status.ENABLED;
            }
            return config;
        }

        private WifiConfiguration IsExsits(String SSID) {
            List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
            for (WifiConfiguration existingConfig : existingConfigs) {
                if (existingConfig.SSID.equals("\"" + SSID + "\""))
                    return existingConfig;
            }
            return null;
        }

    }


}
